package com.example.myapplication.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.myapplication.model.Todo;

import java.util.ArrayList;
import java.util.List;

public class TodoDatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "todo.db"; // 数据库名称
    private static final int DATABASE_VERSION = 2; // 更新版本号
    private static final String TABLE_TODO = "todos"; // 表名

    public TodoDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_TODO + " (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "task TEXT NOT NULL, " +
                "isCompleted INTEGER DEFAULT 0)";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < 2) {
            // 在升级时添加新列
            db.execSQL("ALTER TABLE " + TABLE_TODO + " ADD COLUMN task TEXT NOT NULL DEFAULT ''");
            db.execSQL("ALTER TABLE " + TABLE_TODO + " ADD COLUMN isCompleted INTEGER DEFAULT 0");
        }
    }

    public void addTodo(String task) {
        if (task == null || task.trim().isEmpty()) {
            throw new IllegalArgumentException("Task content cannot be null or empty");
        }

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("task", task);
        values.put("isCompleted", 0); // 默认未完成
        long result = db.insert("todos", null, values);
        db.close();

        if (result == -1) {
            Log.e("TodoDatabaseHelper", "Failed to insert todo");
        } else {
            Log.d("TodoDatabaseHelper", "Todo added with ID: " + result);
        }
    }


    public Cursor getAllTodosCursor() {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.rawQuery("SELECT * FROM todos", null);
    }

    public void updateTodoStatus(int id, boolean isCompleted) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("isCompleted", isCompleted ? 1 : 0);
        db.update(TABLE_TODO, values, "id = ?", new String[]{String.valueOf(id)});
        db.close();
    }

    public List<Todo> getAllTodos() {
        List<Todo> todoList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query("todos", new String[]{"id", "task", "isCompleted"}, null, null, null, null, null);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                try {
                    int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
                    String task = cursor.getString(cursor.getColumnIndexOrThrow("task"));
                    int isCompletedInt = cursor.getInt(cursor.getColumnIndexOrThrow("isCompleted"));

                    boolean isCompleted = isCompletedInt == 1;
                    todoList.add(new Todo(id, task, isCompleted));
                } catch (Exception e) {
                    Log.e("TodoDatabaseHelper", "Error reading todo record", e);
                }
            }
            cursor.close();
        }
        return todoList;
    }

    public void deleteTodoById(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_TODO, "id = ?", new String[]{String.valueOf(id)});
        db.close();
    }

}
